package com.msung.tbea;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerConsumerDemo3 {

    public static class Bread {
        public String name;
        public int count = 1;
        public boolean flag = false;

        public static Lock lock = new ReentrantLock();
        public static Condition condition = lock.newCondition();
    }

    public static class Producer implements Runnable {

        private Bread b;
        Producer(Bread b) {
            this.b = b;
        }

        public void produce(String name) {
            b.name = name + b.count;
            b.count++;
        }

        @Override
        public void run() {
            while(true) {
                Bread.lock.lock();
                try {
                    if(b.flag) {
                        try {
                            Bread.condition.await();
                        } catch (InterruptedException ignored) {

                        }
                    }
                    produce("面包");
                    System.out.println(Thread.currentThread().getName() + "---生产者---" + b.name);
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {

                    }
                    b.flag = true;
                    Bread.condition.signal();
                }finally {
                    Bread.lock.unlock();
                }
            }
        }
    }
}
